# -*- coding:utf-8 -*-
# @Time : 21-8-18 下午2:12 
# @Author : zdy
# @File : UIBlank.py
# desc:
import copy
from UI.Calibration import Ui_Calibration
from Class.VoltSignal import dataBase, VoltSignal
from Class.Factor import Factor
from Class.Format import Format
from Class.Devices import *
from importQT import *

class UIBlank(QDialog, Ui_Calibration):
    def __init__(self, ids):
        super(UIBlank, self).__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.WindowCloseButtonHint)
        self.setFixedSize(self.width(), self.height())
        self.setWindowTitle("空白校正")
        self.chk0.setText(E1)
        self.chk1.setText(E2)
        self.chk2.setText(E3)
        self.chk3.setText(E4)
        self.lblcalValue.setText(self.lblcalValue.text()+"(%)")
        self.applyResource()
        self.ids = ids
        self.chk = [self.chk0, self.chk1, self.chk2, self.chk3]
        self.doubleSpinBox = [self.doubleSpinBox0, self.doubleSpinBox1, self.doubleSpinBox2, self.doubleSpinBox3]
        self.factors = []  # 存储当前/计算出的calibration系数
        self.factorsmass = []
        for i in range(dataBase.maxChannel):
            self.factors.append(device.config.factors[i].blankarea)
            self.factorsmass.append(device.config.factors[i].blankMass)
            enable = device.config.channels[i].enable
            self.chk[i].setEnabled(enable)
            self.doubleSpinBox[i].setEnabled(enable)

        self.updateFactors()
        self.btnCancel.clicked.connect(self.btnCancel_clicked)
        self.btnCalculate.clicked.connect(self.btnCalculate_clicked)
        self.btnOK.clicked.connect(self.btnOK_clicked)
        self.btnReset.clicked.connect(self.btnReset_clicked)

    def applyResource(self):
        self.setWindowIcon(getIcon())

    def updateFactors(self):
        """更新系数列，数据异常时，颜色标识，并禁用OK按钮"""
        error = False
        lbls = [self.lbl0, self.lbl1, self.lbl2, self.lbl3]
        for i in range(dataBase.maxChannel):
            if device.config.channels[i].enable:
                if self.factors[i] !=0 and self.factorsmass[i] !=0:
                    factor =copy.copy(device.config.factors[i])
                    factor.blankarea = 0.0
                    result = Factor.calculateResultFromArea(self.factors[i], self.factorsmass[i],0.0,factor, True)
                    lbls[i].setText(Format.result(result, False))
                else:
                    lbls[i].setText(Format.result(0.0, False))
        if error:
            self.btnOK.setEnabled(False)
        else:
            self.btnOK.setEnabled(True)

    def btnCalculate_clicked(self):
        """根据输入的标准值，重新计算系数"""
        cal = [None] * dataBase.maxChannel  # 存放标准值
        for i in range(dataBase.maxChannel):
            if self.chk[i].checkState() == Qt.Checked:
                cal[i] = self.doubleSpinBox[i].value()
        channel = [[] for i in range(dataBase.maxChannel)]  # 存放calibration=1时计算出的结果
        mass = [[] for i in range(dataBase.maxChannel)]  # 存放calibration=1时计算出的结果
        for id in self.ids:
            # 以下以系数1重新计算当前的结果
            volt = VoltSignal.loadAll(id)
            for i in range(dataBase.maxChannel):
                if cal[i] is not None and volt.channels[i]:
                    factor = copy.copy(device.config.factors[i])
                    factor.blankarea = 0.0
                    area1 = factor.calculateAreaFromStandard(cal[i], volt.sampleWeight,volt.fluxWeight)
                    area2 = factor.calculateArea(volt.listT, volt.listData[i], volt.average[i])

                    if area2 is not None:
                        channel[i].append(area2 - area1)
                        mass[i].append(volt.sampleWeight)
        for i in range(dataBase.maxChannel):
            if len(channel[i]) > 0:
                avr = Factor.calculateAverage(channel[i])
                avr1 = Factor.calculateAverage(mass[i])
                self.factors[i] = avr
                self.factorsmass[i] = avr1
            else:
                self.factors[i] = device.config.factors[i].blankarea  # 不校正的通道恢复原始值
                self.factorsmass[i] = device.config.factors[i].blankMass
        self.updateFactors()
        pass

    def btnCancel_clicked(self):
        self.close()

    def btnOK_clicked(self):
        for i in range(dataBase.maxChannel):
            if self.chk[i].checkState() == Qt.Checked:
                device.config.factors[i].blankarea = self.factors[i]
                device.config.factors[i].blankMass = self.factorsmass[i]
        self.close()

    def btnReset_clicked(self):
        for i in range(dataBase.maxChannel):
            if self.chk[i].checkState() == Qt.Checked:
                self.factors[i] = 0.0
        self.updateFactors()
